//
//  ChooseEmplTimeViewController.m
//  XDBaseFrameWork
//
//  Created by XD-XY on 10/23/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "ChooseEmplTimeViewController.h"

#import "RecipeCollectionHeaderView.h"

@interface ChooseEmplTimeViewController ()
{
    NSMutableArray * emplTimeArray;
    NSMutableArray * nomralArray;
    NSMutableArray * dayArray;
    NSMutableArray * enableArray;
    NSMutableArray * myArray;
    NSString * pesentHour;
    int count;
}
@end

@implementation ChooseEmplTimeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(id)initWithYinPenInfoArray:(NSMutableArray *)array
{
    self = [super init];
    if (self){
        self.yinPenArray = array;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    emplTimeArray = [[NSMutableArray alloc] init];
    nomralArray = [[NSMutableArray alloc] init];
    dayArray = [[NSMutableArray alloc] init];
    dataArray = [[NSMutableArray alloc] init];
    enableArray = [[NSMutableArray alloc] init];
    myArray = [[NSMutableArray alloc] init];
    pesentHour = [[NSString alloc] init];
    
    count = 0;
    self.titleLabel.text = @"请选择拍摄时间";
    
    [self initViews];
    [self performSelector:@selector(initDatas) withObject:nil afterDelay:0];
    
}

#pragma mark
#pragma mark UI 布局
-(void)initViews
{
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing =0;
    flowLayout.minimumLineSpacing =1;
    flowLayout.headerReferenceSize = CGSizeMake(UI_SCREEN_WIDTH,35);
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    mCollectionView = [[UICollectionView alloc] initWithFrame:self.contentView.bounds collectionViewLayout:flowLayout];
    [mCollectionView registerClass:[RiLiCell class] forCellWithReuseIdentifier:@"rilicell"];
    [mCollectionView registerClass:[RecipeCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    mCollectionView.backgroundColor = [UIColor clearColor];
    mCollectionView.alwaysBounceVertical = YES;
    mCollectionView.delegate = self;
    mCollectionView.dataSource = self;
    [self.contentView addSubview:mCollectionView];
    mCollectionView.hidden = YES;
}

#pragma mark UICollectionView Delegate
//设置分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    NSString * s1 = [nomralArray firstObject];
    NSString * s2 = [nomralArray lastObject];
    if ([s1 compare:s2]==0){
        return 1;
    }
    return 2;
}

//每个分区上的元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    int  a = 0;
    if (section == 0){
       NSString * s1 = [nomralArray firstObject];
        for (int i = 0 ; i <[nomralArray count];i++){
            if (![s1 isEqualToString:[nomralArray objectAtIndex:i]]){
                a=i;
                break;
            }
        }
        count = a;
        return a;
    }
    NSString * s2 = [nomralArray lastObject];
    for (int i = 0; i <[nomralArray count];i++){
        if ([s2 isEqualToString:[nomralArray objectAtIndex:i]]){
            a=i;
            break;
        }
    }
    return [nomralArray count]-a;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView * reusableview = nil;

    if(kind == UICollectionElementKindSectionHeader){
        RecipeCollectionHeaderView * headerview = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        if (indexPath.section == 0){
            headerview.titleLB.text = [nomralArray firstObject];
            
        }else{
            headerview.titleLB.text = [nomralArray lastObject];

        }
        reusableview = headerview;
    }
    
    return reusableview;

}

//设置元素内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"rilicell";
    RiLiCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    if (indexPath.section == 0){
        if ([dataArray count]){
            cell.delegate  =self;
            NSDictionary * dict = [dataArray objectAtIndex:indexPath.row];
            cell.dayLB.text = dict[@"day"];
            cell.timeSting = dict[@"ymd"];
            if([dict[@"am"] intValue]==0){
                cell.amBtn.enabled = NO;
            }else{
                cell.amBtn.enabled = YES;
            }
            if([dict[@"pm"] intValue]==0){
                cell.pmBtn.enabled = NO;
            }else{
                cell.pmBtn.enabled = YES;
            }
        
        }
        
    }else{
        if ([dataArray count]){
            cell.delegate  =self;
            NSDictionary * dict = [dataArray objectAtIndex:indexPath.row+count];
            cell.dayLB.text = dict[@"day"];
            cell.timeSting = dict[@"ymd"];

            if([dict[@"am"] intValue]==0){
                cell.amBtn.enabled = NO;
            }else{
                cell.amBtn.enabled = YES;
            }
            if([dict[@"pm"] intValue]==0){
                cell.pmBtn.enabled = NO;
            }else{
                cell.pmBtn.enabled = YES;
            }
        }
    }
    return cell;
}

//设置元素的的大小框
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    UIEdgeInsets top ={0,0,0,0};
    return top;
}

//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(64,29+42.5+42.5+1);
}

//点击元素触发事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}

#pragma mark
#pragma mark RiLiCellDelegate Delegate
-(void)chooseTheEmplTime:(NSString *)mString andAmOrPm:(NSString *)map name:(NSString *)mname
{
    [_delegate chooseTheEmplTimeWithTime:mString amOrPm:map name:mname];
    [self backPrePage];
}

#pragma mark 初始化数据
-(void)initDatas
{
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
    
    for (int i =0;i <=30;i++){
        [comps setDay:+i];
        [comps setHour:0];
        [comps setMinute:0];
        [comps setSecond:0];
        NSDate * nowDate = [calendar dateByAddingComponents:comps toDate:now options:0];
        
        NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
        [dateFormat setDateFormat:@"yyyy-MM"];
        NSString *  locationString = [dateFormat stringFromDate:nowDate];
        [nomralArray addObject:locationString];
        
        [dateFormat setDateFormat:@"dd"];
        [dayArray addObject:[dateFormat stringFromDate:nowDate]];
        
        [dateFormat setDateFormat:@"yyyy-MM-dd"];
        [myArray addObject:[dateFormat stringFromDate:nowDate]];
        
        if (i == 0){
            [dateFormat setDateFormat:@"hh"];
            pesentHour = [NSString stringWithFormat:@"%@",[dateFormat stringFromDate:nowDate]];
        }
    }
    [self getEmplTime];
}

#pragma mark
#pragma mark 获取摄影师时间
-(void)getEmplTime
{
    if (![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    
    ASIHTTPRequest * request = [XDTools postRequestWithDict:@{@"EmplID":[XDTools sharedXDTools].EmplID} API:API_getEmplTime];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            mCollectionView.hidden = NO;
            [emplTimeArray removeAllObjects];
            if (1){
                [emplTimeArray addObjectsFromArray:tmpDict[@"data"][@"EmplUsedTime"]];
                
                NSMutableArray * tmpArray = [[NSMutableArray alloc] init];
                [tmpArray addObjectsFromArray:self.yinPenArray];
                [tmpArray addObjectsFromArray:emplTimeArray];
                
                for (int i =0;i<[myArray count];i++){
                    
                    NSString * s = [myArray objectAtIndex:i];
                    
                    NSMutableDictionary * d = [[NSMutableDictionary alloc] init];
                    [d setValue:s  forKey:@"ymd"];
                    [d setValue:[dayArray objectAtIndex:i] forKey:@"day"];
                    [d setValue:@"1" forKey:@"am"];
                    [d setValue:@"1" forKey:@"pm"];
                    if (i ==0){
                        if([pesentHour intValue]<12){
                            [d setValue:@"0" forKey:@"am"];
                        }else{
                            [d setValue:@"0" forKey:@"am"];
                            [d setValue:@"0" forKey:@"pm"];
                        }
                    }
                    for (NSDictionary * ddict in tmpArray){
                        if ([s isEqualToString:ddict[@"ShootDate"]]){
                            if ([ddict[@"ShootType"] isEqualToString:@"AM"]){
                                [d setValue:@"0" forKey:@"am"];
                            }else if ([ddict[@"ShootType"] isEqualToString:@"PM"]){
                                [d setValue:@"0" forKey:@"pm"];
                            }
                        }
                    }
                    
                    [dataArray addObject:d];
                }
                [mCollectionView reloadData];

            }
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
